var defaultPointIcon = "../img/defaultPoint.png";
var defaultUnbindPointIcon = "../img/defaultUnbindPoint.png";
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var toolbar;
var partLayer;
var centerX = 106.53884704455731;
var centerY = 29.7219072675705;
var currentGraphic;
var drawHandler;
var oldPoint;
require([ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
		"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
		// 控件
		"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
		"esri/dijit/Measurement", "esri/units",
		// 图层
		"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
		"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
		"esri/layers/ArcGISDynamicMapServiceLayer",
		"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/FeatureLayer",
		// 图形要素
		"esri/geometry/Point", "esri/geometry/Polyline",
		"esri/geometry/Polygon", "esri/geometry/Circle",
		// 样式
		"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
		"esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
		"esri/symbols/SimpleFillSymbol",
		// 标签
		"esri/symbols/Font", "esri/layers/LabelClass",
		// 查询
		"esri/tasks/query", "esri/tasks/QueryTask", "esri/toolbars/draw",
		"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom",
		"dojo/dom-construct" ], function(Map, Color, Graphic, InfoTemplate,
		SpatialReference, HeatmapRenderer, OverviewMap, Scalebar, Measurement,
		Units, TDTLayer, TDTAnnoLayer, TDT_ImgLayer, TDT_ImgAnnoLayer,
		GraphicsLayer, ArcGISDynamicMapServiceLayer,
		ArcGISTiledMapServiceLayer, FeatureLayer, Point, Polyline, Polygon,
		Circle, TextSymbol, SimpleMarkerSymbol, PictureMarkerSymbol,
		SimpleLineSymbol, SimpleFillSymbol, Font, LabelClass, Query, QueryTask,
		Draw, Popup, PopupTemplate, dom, domConstruct) {

	map = new Map("map", {
		slider : false,
		logo : false,
		showLabels : true,
		center : [ centerX, centerY ],
		zoom : 14,
		minZoom : 17,
	});

	// 初始化比例尺
	var scalebar = new Scalebar({
		map : map,
		attachTo : "bottom-left",
		scalebarUnit : "dual",
	});

	// 显示比例尺
	scalebar.show();
	drawHandler = Draw;
	var vec = new TDTLayer();// 切片线画图
	var veca = new TDTAnnoLayer();// 切片标注
	var img = new TDT_ImgLayer();
	var imga = new TDT_ImgAnnoLayer();
	map.addLayer(vec);
	map.addLayer(veca);

	map.graphics.on("mouse-down", function(evt) {
		console.log("graphicslayer:mouse-down");
		if (evt.graphic) {
			currentGraphic = evt.graphic;
		}
		if (currentGraphic) {
			oldPoint = evt.mapPoint;
			currentGraphic.isMouseDown = true;
			map.disableMapNavigation();
			map.disablePan();
		}
	});
	map.on("mouse-drag", function(evt) {
		console.log("map:mouse-drag");
		if (currentGraphic) {
			if (currentGraphic.isMouseDown) {
				currentGraphic.setGeometry(evt.mapPoint);
			}
		}
	});
	
	map.on("mouse-up", function(evt) {
		console.log("map:mouse-up");
		if (currentGraphic) {
			oldPoint = null;
			map.enableMapNavigation();
			map.enablePan();
			currentGraphic.isMouseDown = false;
			EditMapPoint(evt);
//			if (currentGraphic.attributes) {
//				if (currentGraphic.attributes.id) {
//					EditMapPoint(evt);
//				}
//			}
		}
	});
	
	//鼠标经过
	map.graphics.on("mouse-over", function(evt) {
		console.log("graphicslayer:mouse-over");
		setPolygonMouseInSymbol(evt.graphic);
		//evt.graphic.setSymbol(symbol);
	});

	//鼠标移开
	map.graphics.on("mouse-out", function(evt) {
		console.log("graphicslayer:mouse-out");
		setPolygonMouseOutSymbol(evt.graphic);
		//evt.graphic.setSymbol(symbol);
	});
	toolbar = new Draw(map);
	dojo.connect(toolbar, "onDrawEnd", addToMap);
	getUnbindPoint();
});

function EditMapPoint(evt) {
	if (evt.graphic) {
		var attr = evt.graphic.attributes;
		editModule(attr);
	}
}
// 添加菜单，弹出弹窗
jQuery('.addPartInMapBtn').on('click', function() {
	var selectNodeId = getTreeIdForSelectNode();
	if (selectNodeId == "" || selectNodeId == "0") {
		message("请选择区域!");
		return;
	}
	$('body').css('cursor', 'url(' + defaultPointIcon + '),auto');
	map.setMapCursor('url(' + defaultPointIcon + '),auto');
	//新增特征点
	toolbar.activate(drawHandler.POINT);
	//toolbar.activate(drawHandler.POLYGON);
});

// 获取当前选择树节点
function getTreeIdForSelectNode() {
	var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree");
	var id = "";
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode && selectNode.id != "0") {
			id = selectNode.id;
		}
	}
	return id;
}



function addToMap(geometry) {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.

	$('body').css('cursor', 'default');
	map.setMapCursor('default');

	map.showZoomSlider(); // 在地图上显示的缩放滑块
	// 判断几何图形的类型
	switch (geometry.type) {
	case "point":
		var symbol = new esri.symbol.PictureMarkerSymbol( defaultPointIcon, 20, 20);
		break;
	case "polyline":
		var symbol = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([ 255,
						0, 0 ]), 1);
		break;
	case "polygon":
		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		break;
	case "extent":
		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		break;
	case "multipoint":
		var symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND, 20,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([ 0, 0, 0 ]), 1), new dojo.Color([ 255,
						255, 0, 0.5 ]));
		break;
	}
	var graphic = new esri.Graphic(geometry, symbol);
	map.graphics.add(graphic); // 将绘图加入到图层中
	currentGraphic = graphic;

	// 打开部件基础信息窗口
	$("#gridAreaEditForm")[0].reset();
	// 打开模态框
	$("#gridAreaModal").modal({
		backdrop : 'static'
	});
	jQuery('#id').val('');
	$("#areaId").val(getTreeIdForSelectNode());
};
// 返回按钮
jQuery('.goBackBtn').on('click',function() {
	if ($("#id").val() == null || $("#id").val() == "") {
		map.graphics.remove(currentGraphic); // 将绘图从图层中移除
		currentGraphic = null;
	} else {
		
		var mapPoint = currentGraphic.geometry;
		mapPoint.setX(currentGraphic.attributes.details[0].longtitude);
		mapPoint.setY(currentGraphic.attributes.details[0].latitude);
		currentGraphic.setGeometry(mapPoint);
	}
});

//放大图标
function setPolygonMouseInSymbol(graphic) {
	var symbol = graphic.symbol;
	if(symbol && symbol.width && symbol.height){
		symbol.width = 30;
		symbol.height = 30;
		graphic.setSymbol(symbol);
	}
	
}

//还原图标
function setPolygonMouseOutSymbol(graphic) {
	var symbol = graphic.symbol;
	if(symbol && symbol.width && symbol.height){
		symbol.width = 20;
		symbol.height = 20;
		graphic.setSymbol(symbol);
	}
	
}

//数据搜索
var graphicArrays = [];
jQuery('.searchMapBtn').on('click',function() {
	graphicArrays = getcurrentGraphicsByValue($("#searchMap").val());
	for (var i = 0; i < graphicArrays.length; i++) {
		if (i == 0) {
			var goPoint = new esri.geometry.Point(graphicArrays[i].geometry.getLongitude(),graphicArrays[i].geometry.getLatitude(),map.spatialReference);
			map.centerAndZoom(goPoint,map.getLevel());
		}
		setPolygonMouseInSymbol(graphicArrays[i]);
	}
});
jQuery('.resetBtnMap').on('click',function() {
	jQuery('#searchMap').val('');
	if(graphicArrays){
		for (var i = 0; i < graphicArrays.length; i++) {
			setPolygonMouseOutSymbol(graphicArrays[i]);
		}
		graphicArrays = null;
	}
});

function getcurrentGraphicsByValue(txt) {
	var graphicArray = [];
	var graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i] && graphics[i].geometry.type == "point") {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.gridIdentify&&graphics[i].attributes.gridIdentify.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				} else if (graphics[i].attributes.gridName&&graphics[i].attributes.gridName.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				} else if (graphics[i].attributes.gridState&&graphics[i].attributes.gridState.title.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				} else if (graphics[i].attributes.gridMemo&&graphics[i].attributes.gridMemo.indexOf(txt) != -1) {
					graphicArray.push(graphics[i]);
					continue;
				}
			}
		}
	}
	return graphicArray;
};

$(function() {
	// 1 初始化分页信息
	initPage();
	// 9 初始化树结构
	initZtree();
	initUnbindDivisionGridPage();
	
});

// 8 撤销查询
jQuery('.resetBtn2').on('click', function() {

	jQuery('#search2').val('');
	serverUbData.key = '';
	serverUbTable.draw();
});
// 7 点击查询按钮
$(".searchBtn2").click(function() {

	serverUbData.key = jQuery("#search2").val();
	serverUbTable.draw();
});

var level;
var serverData = {};
serverData.tree = '';
var serverTable;
// 初始化 层级树
var primaryNode = [];
// //////////////初始化模型的树结构/////////////////////////
var modalSetting = {
	edit : {
		enable : true,
		showRemoveBtn : false,
		showRenameBtn : false,
		drag : {
			isCopy : false,
			isMove : false,
			prev : false,
			next : false,
			inner : false
		}
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "parentId",
			rootParentId : 0
		}
	},
	view : {
		showLine : true
	},
	check : {
		enable : true,
		chkStyle : "radio",
		radioType : "level"
	},
	callback : {
		onClick : bindNodePrepare,
		onNodeCreated : zTreeOnNodeCreated
	}
};
var serverUbData = {};
var serverUbTable;
function initUnbindDivisionGridPage() {
	serverUbTable = jQuery('#unbindDivisionGridTable').DataTable({
		"serverSide" : true,
		"ordering" : false,
		"ajax" : {
			"dataType" : "json",
			"type" : "post",
			"cache" : false,
			"url" : window.rootPath
					+ '/ui/gridAreaPoint/getUnbindPage',
			"data" : function(d) {
				return $.extend({}, d, serverUbData);
			}
		},
		columns : [
				{
					data : null,
					defaultContent : ""
				},
				{
					data : null,
					defaultContent : "",
					render : function(data, type, full, meta) {
						var operate = '<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
								+ '<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>'
								+ '<button type="button" class="btn btn-sm btn-info addNode" title="绑定"><i class="fa fa-sign-in"></i></button>'

						return operate;
					}
				}, {
					data : 'gridIdentify'
				}, {
					data : 'gridName',
				}, {
					data : 'gridArea'
				}, {
					data : 'gridState.title'
				}, {
					data : 'typeOpt.title'
				}, {
					data : "division.divisionName"

				}

		],
		"drawCallback" : function(oSettings) {
			var k = 0;
			var total = oSettings.aiDisplay.length
					+ oSettings._iDisplayStart;
			for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
				$('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
				k++;
			}
			serverUbTable.off('click', 'tr');
			serverUbTable.on('click','tr',function(event) {
				event = event || window.event;
				var target = event.target || event.scrElement;
				var data = serverUbTable.row(this).data();

				if (target.className.indexOf('fa-remove') != -1|| target.className.indexOf('delBtn') != -1) {
					// 2 删除
					deleteGridById(data);
				}

				if (target.className.indexOf('fa-pencil') != -1|| target.className.indexOf('editBtn') != -1) {
					// 3 编辑
					editModule(data);
				}
				if (target.className.indexOf('fa-sign-in') != -1|| target.className.indexOf('addNode') != -1) {
					bindNode(data);
				}
				if (target.className.indexOf('fa-unlock') != -1|| target.className.indexOf('removeNode') != -1) {
					unbindNode(data);
				}
				
				setCenterPoint(data);
				return;
			});
		}
	});

};
// 13 状态选择
$("#gridStateSelect").change(function() {
	var gridStateId = $(this).val();
	var gridStateName = $('#gridStateSelect option:selected').text();
	if (gridStateId == '00000') {
		gridStateName = '';
	}

	serverData.key = jQuery("#search").val();
	serverData.tree = gridStateId;
	serverTable.draw();
});
// 12区域选择
$("#divisionSelect").change(function() {
	var divisionId = $(this).val();
	var divisionName = $('#divisionSelect option:selected').text();
	if (divisionId == '00000') {
		divisionName = '';
	}
	serverData.key = jQuery("#search").val();
	serverData.tree = gridStateId;
	serverTable.draw();
});
// 11 绑定
function bindNode(data) {
	var gridId = data.id;
	var divisionId = $("#divisionId").val();
	if (divisionId == '0' || '' == divisionId) {
		message("选择根节点之外的节点进行绑定!");
		return;
	}
    $("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/bindNode/" + gridId + "/" + divisionId,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				serverTable.draw(false);
				serverUbTable.draw(false);
				//createArea(result.data.data);
				updatePoint(result.data.data);
			}
			message(result.msg);
            $("#right").mLoading("hide");
		}
	});
};
// 10网格绑定区域准备
function bindNodePrepare(e, treeId, treeNode) {
	var divisionId = treeNode.id;

	currentGraphic = null;
	if (divisionId == undefined || '0' == divisionId) {
		return;
	}

	$("#divisionId").val(divisionId);

	// 同时作为过滤条件刷新已绑定信息
	serverData.key = jQuery("#search").val();

	/*
	 * var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree"); var selectNodes =
	 * treeObj.getSelectedNodes(treeObj); if (selectNodes) { var selectNode =
	 * selectNodes[0]; if (selectNode) { serverData.tree = selectNode.id; } }
	 */
	serverData.tree = divisionId;
	serverTable.draw();
	getPoint(divisionId);
};

function getPoint(divisionId){
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/getBindingPointByArea?areaId=" + divisionId,
		dataType : 'json',
		type : 'get',
		contentType : "application/json",
		success : function(result) {
			if (result.code <= 0) {
				message("获取特征点失败!");
			} else {
				if(result.data){
					//map.graphics.clear();
					clearPoint();
					for(var i=0;i<result.data.length;i++){
						createPoint(result.data[i],defaultPointIcon)
						if(i==0){
							var details = result.data[0].details[0];
							var geoPoint = new esri.geometry.Point(details.longtitude,details.latitude,map.spatialReference);
							map.centerAndZoom(geoPoint, map.getLevel());
						}
					}
				}
			}
		}
	});
}

function getUnbindPoint(){
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/getUnBindPointByArea",
		dataType : 'json',
		type : 'get',
		contentType : "application/json",
		success : function(result) {
			if (result.code <= 0) {
				message("获取特征点失败!");
			} else {
				if(result.data){
					//map.graphics.clear();
					//clearPoint();
					for(var i=0;i<result.data.length;i++){
						createPoint(result.data[i],defaultUnbindPointIcon)
					}
				}
			}
		}
	});
}



function clearPoint(){
	var graphics = map.graphics.graphics;
	var len = graphics.length;
	for (var i= len - 1; i >= 0; i--){
		var graphic = graphics[i];
		setPolygonMouseOutSymbol(graphic);
		if(graphic.attributes && graphic.attributes.division){
			map.graphics.remove(graphic);
		}
	}
}

//设置中心点
function setCenterPoint(data){
	var graphics = map.graphics.graphics;
	var len = graphics.length;
	for (var i= len - 1; i >= 0; i--){
		var graphic = graphics[i];
		setPolygonMouseOutSymbol(graphic);
		if(graphic.attributes && graphic.attributes.id == data.id){
//			var geoPoint = new esri.geometry.Point(graphic.attributes.details[0].longtitude ,graphic.attributes.details[0].latitude , map.spatialReference); 
			var geoPoint = new esri.geometry.Point(graphic.geometry.getLongitude(),graphic.geometry.getLatitude(),map.spatialReference);
			
			map.centerAndZoom(geoPoint,map.getLevel());
			setPolygonMouseInSymbol(graphic);
		}
	}
}

//设置绑定
function updatePoint(data){
	var icon;
	var del = false;
	if(data.division){
		if(data.division.id != serverData.tree){
			del = true;
		}
		icon = defaultPointIcon;
	}else{
		icon = defaultUnbindPointIcon;
	}
	var graphics = map.graphics.graphics;
	var len = graphics.length;
	for (var i= len - 1; i >= 0; i--){
		var graphic = graphics[i];
		if(graphic.attributes && graphic.attributes.id == data.id){
			if(del){
				map.graphics.remove(graphic);
			}else{
				var symbol = new esri.symbol.PictureMarkerSymbol(icon, 20, 20);
				//var symbol = graphic.symbol;
				//symbol.url = icon;
				graphic.setSymbol(symbol);
				graphic.attributes = data;
			}
		}
	}
}

function createPoint(data,iconUrl){
	var symbol = new esri.symbol.PictureMarkerSymbol(iconUrl,20,20);
	
	var details = data.details[0];
	var myPoint = {
            "geometry": {
            	"type":"point",
                "x": details.longtitude,
                "y": details.latitude,
                "spatialReference": { "wkid": 4326 }
            },
            "attributes": data,
            "symbol": symbol
            /*,
            "infoTemplate": {
                "title": "sssss",
                "content": "latude:${Field}"
            }*/
        };
	
	var graphic = new esri.Graphic(myPoint);
	//graphic.symbol=symbol;
	graphic.setSymbol(symbol);
	graphic.attributes = data;
	map.graphics.add(graphic);
	return graphic;
}
function getArea(divisionId){
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/getBindingByArea?areaId=" + divisionId,
		dataType : 'json',
		type : 'get',
		contentType : "application/json",
		success : function(result) {
			if (result.code <= 0) {
				message("获取网格失败!");
			} else {
				if (result.data) {
					map.graphics.clear();
					for (var i = 0; i < result.data.length; i++) {
						createArea(result.data[i])
					}
				}
			}
		}
	});
}
function createArea(data) {
	if (data.details) {
		var rings = [];
		var points = [];
		for (var i = 0; i < data.details.length; i++) {
			points.push([]);
		}
		for (var i = 0; i < data.details.length; i++) {
			var point = [];
			point.push(data.details[i].longtitude);
			point.push(data.details[i].latitude);

			points[data.details[i].longlatOrder] = point;
		}
		rings.push(points);
		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		var myPolygon = {
			"geometry" : {
				"rings" : rings,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"symbol" : {
				"color" : [ 0, 0, 0, 64 ],
				"outline" : {
					"outline" : [ 0, 0, 0, 255 ],
					"width" : 1,
					"type" : "esriSLS",
					"style" : "esriSFSSolid"
				}
			}
		};
		var graphic = new esri.Graphic(myPolygon);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.gridDetails = data.details;
		map.graphics.add(graphic);
	}

};
// 设置tree图标大小
function zTreeOnNodeCreated(event, treeId, treeNode) {
	if (treeNode.type != "folder") {
		$('#' + treeNode.tId + '_ico').css(
				"background",
				"url('" + treeNode.icon
						+ "') center center/16px 16px no-repeat");
	}
}
// 9 初始化树结构
function initZtree() {

	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/getAllNodes",
		cache : false,
		type : "get",
		data : '',
		dataType : "json",
		contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
		success : function(data) {
			primaryNode.push({
				id : 0,
				name : "区域层级",
				open : "true"
			// iconSkin:"diy03"
			});
			for (var i = 0; i < data.nodes.length; i++) {
				primaryNode.push(data.nodes[i]);
			}
			$.fn.zTree.init($("#gridAreaTree"), modalSetting, primaryNode);
		}
	});
};
function unbindNode(data) {
	if (data.division == null || undefined == data.division) {
		message("尚未绑定区域");
		return false;
	}
	var id = data.id;
	$("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/unbindNode/" + id,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				serverTable.draw(false);
				serverUbTable.draw(false);
				updatePoint(result.data.data);
			}
			message(result.msg);
            $("#right").mLoading("hide");
		}
	});
};
// 8 撤销查询
jQuery('.resetBtn').on('click', function() {
	jQuery('#search').val('');
	serverData.key = '';

	var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree");
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode) {
			serverData.tree = selectNode.id;
		}
	}
	serverTable.draw();
});
// 7 点击查询按钮
$(".searchBtn").click(function() {
	serverData.key = jQuery("#search").val();
	var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree");
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode) {
			serverData.tree = selectNode.id;
		}
	}
	serverTable.draw();
});
// 6 点击编辑按钮打开模态框
function editModule(data) {
	getcurrentGraphic(data.id);
	$("#gridAreaEditForm")[0].reset();
	// 打开模态框
	$("#gridAreaModal").modal({
		backdrop : 'static'
	});
	// 初始化数据
	// initStateAndTpye();

	// 数据回显
	$("#id").val(data.id);
	$("#gridName").val(data.gridName);
	$("#gridArea").val(data.gridArea);
	$("#gridIdentify").val(data.gridIdentify);
	$("#gridMemo").val(data.gridMemo);
	/*$("#areaId").val(data.areaId);*/
	$("#createTime").val(moment(data.createTime).format('YYYY/MM/DD'));
	$("#gridToArcGisObjectId").val(data.gridToArcGisObjectId);
	$("#gridScale").val(data.gridScale);
	showEditData("#gridState", data.gridState.id);
	if(data.typeOpt){
		showEditData("#typeOpt", data.typeOpt.id);
	}
	
	if(data.division){
		showEditData("#areaId", data.division.id);
	}else{
		jQuery("#areaId").val('');
	}
	

	$("#typeOpt").prop("disabled", "disabled").css("background-color",
			"#BEBEBE");

	$("#gridIdentify").prop("readonly", "readonly");
};

function showEditData(str, data) {
	$(str).each(function() {
		$(this).children("option").each(function() {
			if ($(this).val() == data) {
				$(this).prop("selected", true);
			}
		});
	});
}
function getcurrentGraphic(data) {
	var graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.id == data) {
					currentGraphic = graphics[i];
					return;
				}
			}
		}
	}
	currentGraphic=null;
};
// 5 点击保存按钮添加单元网格信息
$(".saveBtn").click(function() {
	var gridAreaDetail = [];
	/*
	if(currentGraphic){
		var geometry = currentGraphic.geometry;
		for (var i = 0; i < geometry.rings[0].length; i++) {
			var point = {
				"longtitude" : geometry.rings[0][i][0],
				"latitude" : geometry.rings[0][i][1],
				"longlatOrder" : i
			};
			gridAreaDetail.push(point);
		}
	}
	*/
	var geometry = currentGraphic.geometry;
	var point = {
			"longtitude" : geometry.x,
			"latitude" : geometry.y,
			"longlatOrder" : 0
		};
	gridAreaDetail.push(point);
	var stateId = $("#gridState").val();
	var typeId = $("#typeOpt").val();
	var typeName = $("#typeOpt option:selected").text();

	var id = $("#id").val();

	var gridArea = $("#gridArea").val();

	var gridMemo = $("#gridMemo").val();
	var areaId = $("#areaId").val();
	var gridToArcGisObjectId = $("#gridToArcGisObjectId").val();
	var createTime = $("#createTime").val();
	var gridName = $("#gridName").val();
	var gridScale = $("#gridScale").val();
	var data = {};
	// var gridAreaInfo = {};


	if (id == '') {// 添加
		gridAreaInfo = {
			"gridArea" : gridArea,
			"gridName" : gridName,
			"gridScale" : gridScale,
			// "gridIdentify" : gridIdentify,
			"gridMemo" : gridMemo,
			"gridToArcGisObjectId" : gridToArcGisObjectId,
			"gridState" : {
				"id" : stateId
			},
			"typeOpt" : {
				"id" : typeId
			}/*,
			"division" : {
				"id" : areaId
			}*/
		};
		if(areaId!=undefined&&areaId!=""){
			gridAreaInfo.division={
				"id" : areaId
			};
		}
		data = {
			"gridAreaInfo" : gridAreaInfo,
			"gridAreaDetail" : gridAreaDetail
		};
	} else {// 修改
		var gridIdentify = $("#gridIdentify").val();
		// 解绑之后
		/*if (areaId == null || '' == areaId) {
			message("请绑定区域");
			return;
		}*/

		gridAreaInfo = {
			"id" : id,
			"gridArea" : gridArea,
			"gridScale" : gridScale,
			"gridIdentify" : gridIdentify,
			"gridName" : gridName,
			"gridMemo" : gridMemo,
			"gridToArcGisObjectId" : gridToArcGisObjectId,
			// "updateTime":updateTime,
			"createTime" : createTime,
			"gridState" : {
				"id" : stateId
			},
			"typeOpt" : {
				"id" : typeId
			}/*,
			"division" : {
				"id" : areaId
			}*/
		};
		if(areaId!=undefined&&areaId!=""){
			gridAreaInfo.division={
				"id" : areaId
			};
		}
		data = {
			"gridAreaInfo" : gridAreaInfo,
			"gridAreaDetail" : gridAreaDetail
		};
	}
    $("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/operateGrid",
		dataType : 'json',
		data : JSON.stringify(data),
		type : 'post',
		contentType : "application/json",
		success : function(result) {
			if (result.code == 1) {
				if(currentGraphic){
					currentGraphic.attributes = result.data.attributes;
					currentGraphic.gridDetails = result.data.gridDetails;
				}
				jQuery('#gridAreaModal').modal('hide');
				serverTable.draw(false);
				serverUbTable.draw(false);
				updatePoint(result.data.attributes);
			}
			message(result.msg);
            $("#right").mLoading("hide");
		}
	});
})
// 4 准备预先的数据[状态,类型]
function initStateAndTpye() {
	$("#typeOpt option").remove();
	$("#gridState option").remove();
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/initStateAndTpye",
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				var types = result.data.type;
				var states = result.data.state;
				$.each(types, function() {
					$("#typeOpt").append(
							"<option value='" + this.id + "'>" + this.title
									+ "</option>");
				});
				$.each(states, function() {
					$("#gridState").append(
							"<option value='" + this.id + "'>" + this.title
									+ "</option>");
				});
			}
		}
	});
};
// 3 点击添加按钮弹出模态框
$(".addBtn").click(function() {
	jQuery('#id').val('');
	$("#gridAreaEditForm")[0].reset();
	// 打开模态框
	$("#gridAreaModal").modal({
		backdrop : 'static'
	});
	$("#areaId").val(getTreeIdForSelectNode());

	/*
	 * var treeObj = $.fn.zTree.getZTreeObj("gridAreaTree"); var selectNodes =
	 * treeObj.getSelectedNodes(treeObj); if (selectNodes) { var selectNode =
	 * selectNodes[0]; if (selectNode) { $("#areaId").val(selectNode.id); } }
	 */
	// 4 准备预先的数据[状态,类型]
	// initStateAndTpye();
});
// 2 删除网格信息
function deleteGridById(data) {
	var gridId = data.id;
    $("#right").mLoading("show");
	$.ajax({
		url : rootPath + "/ui/gridAreaPoint/operateGrid/" + gridId,
		dataType : 'json',
		type : 'POST',
		data : '_method=DELETE',
		success : function(result) {
			if (result.code == 1) {
				serverTable.draw(false);
				serverUbTable.draw(false);
				deleteAreaMap(data);
			}
			message(result.msg);
            $("#right").mLoading("hide");
		}
	});
}
function deleteAreaMap(data) {
	/*
	 * var graphics = map.graphics.graphics; for (var i=0;i<graphics.length;i++) {
	 * if (graphics[i]) { if(graphics[i].attributes){
	 * if(graphics[i].attributes.id==data.id){
	 * console.log("remove:"+graphics[i].attributes.id);
	 * map.graphics.remove(graphics[i]); break; } } } }
	 */
	getcurrentGraphic(data.id);
	if (currentGraphic) {
		map.graphics.remove(currentGraphic);
	}
}
// 1 初始化分页信息
function initPage() {

	serverTable = jQuery('#bindDivisionGridTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "post",
							"cache" : false,
							"url" : window.rootPath + '/ui/gridAreaPoint/getpage',
							"data" : function(d) {
								return $.extend({}, d, serverData);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : null,
									defaultContent : "",
									render : function(data, type, full, meta) {
										var operate = '<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
												+ '<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>'

												+ '<button type="button" class="btn btn-sm btn-danger removeNode" title="解绑"><i class="fa fa-unlock"></i></button>';
										return operate;
									}
								}, {
									data : 'gridIdentify'
								}, {
									data : 'gridName',
								}, {
									data : 'gridArea'
								}, {
									data : 'gridState.title'
								}, {
									data : 'typeOpt.title'
								}, {
									data : "division.divisionName"

								}

						],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}
							serverTable.off('click', 'tr');
							serverTable
									.on(
											'click',
											'tr',
											function(event) {
												event = event || window.event;
												var target = event.target
														|| event.scrElement;
												var data = serverTable
														.row(this).data();

												if (target.className
														.indexOf('fa-remove') != -1
														|| target.className
																.indexOf('delBtn') != -1) {
													// 2 删除
													deleteGridById(data);
												}

												if (target.className
														.indexOf('fa-pencil') != -1
														|| target.className
																.indexOf('editBtn') != -1) {
													// 3 编辑
													editModule(data);
												}
												if (target.className
														.indexOf('fa-sign-in') != -1
														|| target.className
																.indexOf('addNode') != -1) {
													bindNode(data);
												}
												if (target.className
														.indexOf('fa-unlock') != -1
														|| target.className
																.indexOf('removeNode') != -1) {

													unbindNode(data);
												}
												setCenterPoint(data);
												return;
											});
						}
					});

};